<template>
  <div class="box">
    <div id="container"></div>
  </div>
</template>

<script>
import AMap from "AMap"; // 引入高德地图
import { location } from "@/assets/javascript/map.js";
export default {
  data() {
    return {
      city: "",
      cityIP: ""
    };
  },
  mounted() {
    this.getLocation(); // 调用获取地理位置
  },
  methods: {
    /**获取地图定位*/
    getLocation() {
      // AMap.Geolocation 插件
      let _that = this;
      let geolocation = location.initMap("container"); //定位
      AMap.event.addListener(geolocation, "complete", result => {
        //返回定位信息
        _that.city = result.formattedAddress;
        console.log(_that.city);
      });

      AMap.event.addListener(geolocation, "error", onError => {
        //返回定位出错信息
        console.log(onError);
        _that.city = "定位失败";
        _that.getLatLngLocation();
      });
    },

    getLatLngLocation() {
      //  根据IP返回对应城市信息
      let this_ = this;
      AMap.plugin("AMap.CitySearch", function() {
        let citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function(status, result) {
          if (status === "complete" && result.info === "OK") {
            // 查询成功，result即为当前所在城市信息
            AMap.plugin("AMap.Geocoder", function() {
              let geocoder = new AMap.Geocoder({
                // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                city: result.adcode
              });
              let lnglat = result.rectangle.split(";")[0].split(",");
              geocoder.getAddress(lnglat, function(status, data) {
                if (status === "complete" && data.info === "OK") {
                  // data为对应的地理位置详细信息
                  console.log(data);
                  this_.cityIP = data.regeocode.formattedAddress;
                } else {
                  this_.cityIP = "定位失败";
                }
              });
            });
          }
        });
      });
    }
  }
};
</script>
